package controllers;

import java.util.Date;
import java.util.List;

import models.Commodity;
import models.BaseEntity.PeopleType;
import models.Commodity.OnSaleStatus;
import models.QueryBean;
import models.ShoppingCar;
import models.User;
import play.mvc.Controller;
import play.mvc.With;
import service.CommoditiesService;

@With(Secure.class)
public class ShoppingCars extends Controller {
	
	/**
	 * 从购物车中移除商品。
	 * @param id
	 */
	public static void shoppingCarRemove(long id) {
		ShoppingCar.delete("id = ?", id);
	}
	/**
	 * 从购物车中移除商品。
	 * @param id
	 */
	public static void shoppingCarRemoveAll() {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		ShoppingCar.delete("user.id = ?", user.id);
	}
	/**
	 * 保存批量修改的购物车。
	 * @throws Exception 
	 */
	public static String saveShoppingCars() throws Exception {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		int i = 0;
		while (true) {
			String idStr = request.params.get("shoppingCars[" + i + "].id");
			if(ValidationUtil.isEmpty(idStr)) break;
			long id = Long.valueOf(idStr);
			String quantity = request.params.get("shoppingCars[" + i + "].quantity");
			if(!ValidationUtil.isLong(quantity)){
				String errMsg = "购买数量必须为字母。";
				throw new Exception(errMsg);
			}
			ShoppingCar shoppingCar = ShoppingCar.findById(id);
			if(shoppingCar == null){
				String errMsg = "购物车项（id:"+ id +"）已经被移出购物车。";
				throw new Exception(errMsg);
			}
			shoppingCar.quantity = Long.valueOf(quantity);
			shoppingCar.remark = request.params.get("shoppingCars[" + i + "].remark");
			shoppingCar.resetModifier(user);
			shoppingCar.save();
			++i;
		}
		return "";
	}
	
	public static void buyCommodity() throws Exception {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		int i = 0;
		while (true) {
			String idStr = request.params.get("commodity[" + i + "].id");
			if(ValidationUtil.isEmpty(idStr)) break;
			long id = Long.valueOf(idStr);
			String quantity = request.params.get("commodity[" + i + "].quantity");
			if(!ValidationUtil.isLong(quantity)){
				String errMsg = "购买数量必须为字母。";
				throw new Exception(errMsg);
			}
			CommoditiesService.buy(id, Integer.valueOf(quantity), null, user, user);
			++i;
		}
	}
	
	/**
	 * 校验是否可以生成订单。
	 * @throws Exception 
	 */
	public static void validateShoppingCarLogic() throws Exception {
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		List<ShoppingCar> shoppingCars = ShoppingCar.find("user.id", user.id).fetch();
		if(ValidationUtil.isEmpty(shoppingCars)) 
			throw new Exception("购物车内没有任何商品。");
		
		for(ShoppingCar shoppingcar : shoppingCars) {
			Commodity commodity = shoppingcar.commodity;
			if(OnSaleStatus.OFFSALE == commodity.onSaleStatus 
					|| (OnSaleStatus.ONSALE_LIMITED == commodity.onSaleStatus 
							&& commodity.quantityLeft < shoppingcar.quantity)) {
				throw new Exception("货物["+commodity.name+"]\\编号["+commodity.SN+"]仓库存货不足，请修改购买数量。");
			}
		}
	}
	
	/**
	 * 
	 * @param queryBean
	 */
	public static void shoppingCar(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
		}
		
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		
		StringBuilder sql = new StringBuilder();
		sql.append("user.id = ?");
		sql.append("order by createAt, lastModifiedAt desc");
		
		//页数计算
		queryBean.totalQuantity = new ShoppingCar().count(sql.toString(), user.id);
		queryBean.totalPage = queryBean.totalQuantity/queryBean.quantityEachPage;
		if(queryBean.totalQuantity%queryBean.quantityEachPage > 0) queryBean.totalPage++;
		if(queryBean.totalPage < queryBean.currentPage) {
			queryBean.currentPage = queryBean.totalPage;
		}
		
		List<ShoppingCar> shoppingCars = ShoppingCar.find(sql.toString(), user.id)
			.fetch((int)queryBean.currentPage, queryBean.quantityEachPage);
		if(shoppingCars != null) {
			for(ShoppingCar sc : shoppingCars) {
				CommoditiesService.setCommodityPriceByUser(sc.commodity, user);
			}
		}
		
		render("@Users.shoppingCar", shoppingCars, queryBean);
	}
	
	/**
	 * 购买指定数量的商品。
	 * @param commodityId
	 * @param quantity
	 * @throws Exception
	 */
	public static void buy(long commodityId, String quantity) throws Exception {
		if(!ValidationUtil.isLong(quantity)) {
			throw new RuntimeException("购买数量必须为数字类型");
		}
		String username = session.get(GlobalVariables.SECURE_USERNAME);
		User user = User.find("byUsername", username).first();
		CommoditiesService.buy(commodityId, Integer.valueOf(quantity), null, user, user);
	}
}

